package com.pz.gulimall.auth.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson2.JSON;
import com.pz.gulimall.auth.service.ShopCarService;
import com.pz.gulimall.auth.vo.User;
import com.pz.gulimall.auth.vo.res.ShopCarItemResVo;
import com.pz.gulimall.common.exception.BizCodeEnum;
import com.pz.gulimall.common.exception.RRException;
import com.pz.gulimall.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutionException;

@RestController
@RequestMapping("user/shop-car")
public class ShopCarController {
    @Autowired
    private ShopCarService shopCarService;

    /**
     * 获取当前登录用户的购物车的购物项
     */
    @GetMapping("/getCartIems")
    public R getCatItems(){
        List<ShopCarItemResVo> cartItems = shopCarService.getCartItems(getLoginId());
        Collections.reverse(cartItems);
        return R.ok().put("data", cartItems);
    }

    /**
     * 登录用户添加购物项
     * @param skuId skuID
     * @param count 数量
     */
    @PostMapping("/addItem")
    public R addItems(@RequestParam("skuId") Long skuId, @RequestParam("count") int count){
        if(count < 0){
            return R.error(BizCodeEnum.AUTH_Illegal_COUNT.getCode(), BizCodeEnum.AUTH_Illegal_COUNT.getMsg());
        }
        try {
            shopCarService.addItem(getLoginId(),skuId,count);
        } catch (ExecutionException | InterruptedException e) {
            e.printStackTrace();
            throw new RRException(BizCodeEnum.THREAD_EXCEPTION.getMsg(), BizCodeEnum.THREAD_EXCEPTION.getCode());
        }
        return R.ok("成功添加商品！");
    }

    /**
     * 登录用户删除购物车中的商品
     * @param skuIds 要删除的 skuId集合
     */
    @RequestMapping("/delItem")
    public R delItem(@RequestBody List<Long> skuIds){
        shopCarService.delItem(getLoginId(), skuIds);
        return R.ok("移除成功");
    }

    private String getLoginId(){
        User user = JSON.to(User.class, StpUtil.getSession().get("user"));
        String loginId;
        if(user.getMobile() != null && !StringUtils.isEmpty(user.getMobile())){
            loginId = user.getMobile();
        } else if(user.getUsername() != null && !StringUtils.isEmpty(user.getUsername())){
            loginId = user.getUsername();
        } else {
            throw new RRException(BizCodeEnum.AUTH_SHOPCAR_NO_ID.getMsg(),BizCodeEnum.AUTH_SHOPCAR_NO_ID.getCode());
        }
        return loginId;
    }
}
